package it.antonioduca.citt;

import java.util.List;

import it.antonioduca.citt.ICittService;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class CittActivity extends Activity implements OnCheckedChangeListener {
	
	private final String TAG = "Citt";
	
	private CheckBox cb1;
	private Intent intent;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setTitle(getString(R.string.app_name) + " " + getString(R.string.version));
        cb1 = (CheckBox)findViewById(R.id.checkBox1);
        
        if(verifySensors()) {
            intent = new Intent();
            intent.setClassName("it.antonioduca.citt","it.antonioduca.citt.CittService");
            bindService(intent, mConnection, 0);
            cb1.setOnCheckedChangeListener(this);
        } else {
        	cb1.setEnabled(false);
        	cb1.setText("Sensors not supported!");
        }
    }
	
	private boolean verifySensors() {
		boolean check = false;
        SensorManager mgr = (SensorManager)getSystemService(SENSOR_SERVICE);
        List<Sensor> sensors = mgr.getSensorList(Sensor.TYPE_ALL);
        for (Sensor sensor : sensors)
        	if(sensor.getType()==Sensor.TYPE_ORIENTATION)
        		check = true;
        return check;
	}
    
    @Override
	protected void onDestroy() {
		unbindService(mConnection);
		super.onDestroy();
    }

    private ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "Service connected");
            ICittService.Stub.asInterface(service);
            cb1.setChecked(true);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "Service disconnected");
            cb1.setChecked(false);
		}
    };

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		SharedPreferences settings = getSharedPreferences(getString(R.string.properties_filename), MODE_PRIVATE);
		SharedPreferences.Editor prefEditor = settings.edit();
		prefEditor.putBoolean("enabled", isChecked);
		prefEditor.commit();
		if(isChecked) {
			startService(intent);
			cb1.setText(R.string.enabled);
			Log.i(TAG, "Service is ACTIVE.");
		} else {
			stopService(intent);
			cb1.setText(R.string.disabled);
			Log.i(TAG, "Service is NOT ACTIVE.");
		}
	}
}